templateViewInit = ()=>{

    searchFormInfo();

    // 已知数据渲染
    var inst = table.render({
        elem: '#user-list',
        id:'user-list-id',
        height: '#content-body-210',
        url: top.tools.getBaseUrl()+'/user/getPage',
        method: 'post',
        headers:{
            'Access-Token':top.tools.cookie.token(),
            'Content-Type':'application/json',
        },
        toolbar: '#userToolbar',
        defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
            title: '提示',
            layEvent: 'LAYTABLE_TIPS',
            icon: 'layui-icon-tips',
            onClick: function (obj) { // 2.9.12+
                layer.alert('自定义工具栏图标按钮');
            }
        }],
        cols: [
            [
                {type: 'checkbox', width: 50},
                {type: 'numbers', title: '序号', align: 'center', width: 60},
                {field: 'avatar', title: '头像', align: 'center', width: 60,templet:function (d){
                        // 返回模板内容
                        return '<div class="jmAvatar xxl xs" onclick="clickImgView(this)" id="'+d.id+'" avatar="'+d.avatar+'"></div>'
                    }},
                {field: 'username', title: '用户账号', align: 'center', minWidth: 100},
                {field: 'nickname', title: '用户名称', align: 'center',minWidth: 100},
                {field: 'sex', title: '性别', align: 'center',width: 60,templet:function (d){
                       return  top.tools.dict().getDictLabel('system_user_sex',d.sex);
                    }},
                {field: 'mobile', title: '手机号码', align: 'center',width: 120},
                {field: 'email', title: '邮箱', align: 'center',width: 180},
                {field: 'status', title: '账号状态', align: 'center',width:100,templet:function (d){
                        return '<input type="checkbox" name="status" id="'+d.id+'" value="'+d.status+'" ' +
                            'title="启用|停用" lay-skin="switch" lay-filter="user-status" '+( d.status ? "checked" : "" )+'>';
                    }},
                {field: 'loginDate', title: '最后登录时间',align: 'center', width: 160,templet:function (d) {
                        return top.tools.form.formatDate(d.loginDate);
                    }},
                {field: 'role', title: '角色', align: 'center',width: 60,templet: function (d){
                        return '<a href="javascript:;" class="a-name" onclick="openRoleData(\''+d.id+'\')" >'+d.role+'</a>';
                    }},
                {field: 'resources', title: '资源', align: 'center',width: 60,templet: function (d){
                        return '<a href="javascript:;" class="a-name" onclick="openResourcesData(\''+d.id+'\')" >'+d.resources+'</a>';
                    }},
                {fixed: 'right', title: '操作', align: 'center', width: 180, minWidth: 125, toolbar: '#barDemo'}
            ]
        ],
        parseData: dataToFormat,
        //skin: 'line', // 表格风格
        //even: true,
        page: true, // 是否显示分页
        limits: [15, 20, 30,50],
        limit: 15, // 每页默认显示的数量
        done: function (res, curr, count) {
            $(".layui-table th[data-field=" + 0 + "] .layui-table-cell").html("");
            $('td .jmAvatar').each(function (i,elem){
                top.tools.file().downloadFile({
                    elem:elem,
                    avatar:$(elem).attr("avatar")
                })
            })
        }
    });

    // 工具栏事件
    table.on('toolbar(user-list)', function (obj) {
        var id = obj.config.id;
        var checkRow = table.checkStatus(id);

        var data = checkRow.data;
        if (obj.event === 'add') {
            openForm({
                title:"新增用户",
                btn:1,
                save:(closeid)=>{
                    formFun.save(inst,closeid)
                },
                reset:(closeid)=>{
                    form.val('user_form', top.tools.form.getFindElementOnObj("#lay-user-form",false));
                },
                before:(index,layero,that,isEdit)=>{
                    workdbFieldConvert(document.querySelectorAll('#lay-user-form .dict-module'),isEdit);
                    formFun.uploadAvatar();
                    form.val('user_form', {
                        sort:inst.config.page.count+1,
                        status:true
                    });
                },
                area:'40%'
            },'user_form')
        } else if (obj.event === 'update') {
            if (checkRow.data.length<=0){
                layer.msg("请选择数据！");
                return
            }
            openForm({
                title:"查看用户",
                btn:-1,
                area:'40%',
                before:(index,layero,that,isEdit)=>{
                    $('input[type=password]').parents('.layui-form-item').remove();
                    workdbFieldConvert(document.querySelectorAll('#lay-user-form .dict-module'),isEdit);
                    formFun.uploadAvatar(data.avatar,false);
                    form.val('user_form', data);
                }
            },'user_form')
        } else  if (obj.event === 'del') {
            if (checkRow.data.length<=0){
                layer.msg("请选择数据！");
                return
            }
            let ids = data.map((user) => user.id);
            openConfirm(()=>{
                formFun.remove({
                    id:ids.join(',')
                },inst)
            });
        } else if (obj.event === 'resetPassword'){
            if (checkRow.data.length<=0){
                layer.msg("请选择数据！");
                return
            }
            openForm({
                title:"重置密码",
                btn:1,
                save:(closeid)=>{
                    let formData = top.tools.form.getFindElementOnObj("#lay-reset-password-form",true);
                    formData.id = data[0].id;
                    top.API.user().updatePassword(formData,(res)=>{
                        layer.msg(res.message, {icon: 1});
                        if (closeid){
                            layer.close(closeid);
                        }
                    })
                },
                reset:(closeid)=>{
                    form.val('reset-password-form', top.tools.form.getFindElementOnObj("#lay-reset-password-form",false));
                },
                area:'20%',
                before:(index,layero,that,isEdit)=>{

                }
            },'reset-password-form')
        }
    });
// 触发单元格工具事件
    table.on('tool(user-list)', function (obj) { // 双击 toolDouble
        var data = obj.data; // 获得当前行数据
        if (obj.event === 'edit') {
            openForm({
                title:"编辑用户",
                btn:1,
                save:(closeid)=>{
                    formFun.save(inst,closeid)
                },
                reset:(closeid)=>{
                    form.val('user_form', top.tools.form.getFindElementOnObj("#lay-user-form",false));
                },
                area:'40%',
                before:(index,layero,that,isEdit)=>{
                    $('input[type=password]').parents('.layui-form-item').remove();
                    $('#lay-user-form input[name=username]').attr("disabled","disabled")
                    workdbFieldConvert(document.querySelectorAll('#lay-user-form .dict-module'),isEdit);
                    formFun.uploadAvatar(data.avatar);
                    formFun.setValue(data,'user_form')
                }
            },'user_form')
        } else if (obj.event === 'view') {
            openForm({
                title:"查看资源",
                btn:-1,
                area:'40%',
                before:(index,layero,that,isEdit)=>{
                    $('input[type=password]').parents('.layui-form-item').remove();
                    workdbFieldConvert(document.querySelectorAll('#lay-user-form .dict-module'),isEdit);
                    formFun.uploadAvatar(data.avatar,false);
                    formFun.setValue(data,'user_form')
                }
            },'user_form')
        } else if (obj.event === 'del') {
            openConfirm(()=>{
                formFun.remove(data,inst)
            });
        }
    });
    queryButton('user-list-id');
    formReset();
    // 状态 - 开关操作
    form.on('switch(user-status)', function(obj){
        let data = {
            id:$(obj.elem).attr("id"),
            status:obj.elem.checked? 1:0
        }
        top.API.user().save(data,()=>{
            table.reloadData('user-list-id', {
                where: {}, // 数据异步请求时携带的字段集 --- 属性设置有效，因属于数据相关属性
                scrollPos: true, // 设定重载数据或切换分页时的滚动条的位置状态 --- 属性设置有效
                page: {
                    curr: inst.config.page.curr,
                    limit: inst.config.page.limit
                }
            });
        })
    });
}
function setPassword(){
    $('input[name=password]').val(top.tools.form.generatePassword());
}
var formFun = {
    uploadAvatar:function (avatar,type=true) {
        var fileList;
        if (type){
            let uploadListIns  = top.tools.file().uploadFile({
                elem: '#upload-avatar',
                accept:'images',
                drag:false,
                choose:function (obj){
                    let that = this
                    obj.preview(function(index, file, result){
                        if (fileList[index]){
                            delete fileList[index]
                            delete that.files[index]
                        }
                    });
                },
                before:function (obj){
                    // 将每次选择的文件追加到文件队列
                    fileList = this.files = obj.pushFile();
                    // 预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                    obj.preview(function(index, file, result){
                        // 得到文件索引
                        // 得到文件对象
                        // 得到文件base64编码，比如图片
                        if ( $("#upload-avatar i").length>0){
                            $("#upload-avatar i").attr("src",result);
                            $("#upload-avatar").find("i").attr("class","layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop");
                        }else {
                            $("#upload-avatar").html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" src="'+result+'" </i>')
                        }
                    });
                },
                done: function(res){
                    if (res.code === 200){
                        layer.msg('上传成功');
                        $("#upload-avatar").html('<img src="'+$("#upload-avatar i").attr("src")+'">');
                        $("input[name=avatar]").val(res.data)
                    }else {
                        $("#upload-avatar").html('<i class="layui-icon layui-icon-close-circle"></i>')
                    }
                }
            })
        }
        if (avatar){
            top.tools.file().downloadFile({
                elem: '#upload-avatar',
                avatar
            })
        }
    },
    save:(userTable,closeid)=>{
        let formData = top.tools.form.getFindElementOnObj("#lay-user-form",true);
        if (typeof formData === 'boolean'){
            return;
        }
        if (formData.status && formData.status === 'on' ){
            formData.status = 1;
        }else {
            formData.status = 0;
        }

        top.API.user().save(formData,(res)=>{
            layer.msg(res.message, {icon: 1}, function(){
                // layer.msg('提示框关闭后的回调');
                if (userTable){
                    table.reloadData('user-list-id', {
                        scrollPos: true, // 设定重载数据或切换分页时的滚动条的位置状态 --- 属性设置有效
                        page: {
                            curr: userTable.config.page.curr,
                            limit: userTable.config.page.limit
                        }
                    });
                }
                if (closeid){
                    layer.close(closeid);
                }
            });
        })
    },
    remove:(data,userTable)=>{
        top.API.user().delUser(data,(res)=>{
            layer.msg(res.message, {icon: 1}, function(){
                // layer.msg('提示框关闭后的回调');
                if (userTable){
                    table.reloadData('user-list-id', {
                        scrollPos: true, // 设定重载数据或切换分页时的滚动条的位置状态 --- 属性设置有效
                        page: {
                            curr: userTable.config.page.curr,
                            limit: userTable.config.page.limit
                        }
                    });
                }
            });
        })
    },
    setValue:(data,eleId)=>{
        data.status = parseInt(data.status);
        form.val(eleId, data);
    }
}

function openResourcesData(userId){
    top.API.common().loadPage('page/from-component/MenuModule.html',function (response){
        openForm({
            title:"分配资源",
            btn:-1,
            area:'50%',
            before:(closeid,layero,that)=>{
                top.tools.loading()
                $(layero).find('.layui-layer-content').attr("layui-width",$(layero).outerWidth())
                $(layero).find('.layui-layer-content').attr("userId",userId)
                $(layero).hide();
                let intervalId = setInterval(()=>{
                    var obj = top.tools.cache.get('resourcesFrom');
                    if (obj && obj.resourcesFrom === 'true'){
                        layui.layer.close(loadingId);
                        clearInterval(intervalId);
                        // 获取浏览器视口的高度
                        const viewportHeight = window.innerHeight;
                        var popupHeight = $(layero).outerHeight();
                        var topPosition = (viewportHeight - popupHeight) / 2;
                        $(layero).css('top', topPosition+'px');
                        $(layero).show();
                        top.tools.cache.remove('resourcesFrom')
                    }
                },500)
            }
        },null,response);
    })
}

function openRoleData(userId){
    top.API.common().loadPage('page/from-component/RoleModule.html',function (response){
        openForm({
            title:"分配角色",
            btn:1,
            area:'50%',
            save:(closeid,layero,that)=>{
                let data = treeTable.checkStatus('role-list-id',true).data;
                if (data.length > 0){
                    let roleids = [];
                    layui.each(data,function (index,item){
                        roleids.push({
                            userId:userId,
                            roleId:item.id
                        })
                    })
                    top.API.user().bindRole({
                        id:userId,
                        roleList:roleids
                    },(res)=>{
                        layer.msg(res.message, {icon: 1},function (){
                            table.reloadData('user-list-id')
                            if (closeid){
                                layer.close(closeid);
                            }
                        })
                    })
                }else {
                    layer.msg("没有选中数据",{icon:2})
                }
            },
            reset:(closeid,layero,that)=>{
                form.val('from-reset-val-filter', top.tools.form.getFindElementOnObj($(layero).find(".search-criteria"),false));
            },
            before:(closeid,layero,that)=>{
                $(layero).find('.layui-layer-content').attr("layui-width",$(layero).outerWidth())
                $(layero).find('.layui-layer-content').attr("userId",userId)
                $(layero).hide();
                let intervalId = setInterval(()=>{
                    var obj = top.tools.cache.get('roleFrom');
                    if (obj && obj.roleFrom === 'true'){
                        clearInterval(intervalId);
                        // 获取浏览器视口的高度
                        const viewportHeight = window.innerHeight;
                        var popupHeight = $(layero).outerHeight();
                        var topPosition = (viewportHeight - popupHeight) / 2;
                        $(layero).css('top', topPosition+'px');
                        $(layero).show();
                        top.tools.cache.remove('roleFrom')
                    }
                },500)
            }
        },null,response);
    })
}